<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布订阅模式</title>
</head>
<body>
    <script>
        var event = (function(){
            eventObjs = {}

            return {
                on:function(type,handler){
                    (eventObjs[type] || (eventObjs[type] = [])).push(handler)
                },

                off:function(type,handler){
                    if(arguments.length === 0){
                        eventObjs = {}
                    }else if(arguments.length === 1){
                        eventObjs[type] = []

                    }else{
                        let _event = eventObjs[type]
                        if(!_event) return 
                        for(let i = _event.length-1; i >= 0; i--){
                            if(_event[i] === handler){
                                _event.splice(i,1)
                            }
                        }
                    }
                },

                emit:function(type){
                    let args = Array.prototype.slice.call(arguments,1)
                    let _event = eventObjs[type]
                    if(!_event) return
                    for(let i = 0; i < _event.length; i++){
                        _event[i].apply(null,args)
                    }
                }
            }

        }()

        )
        </script>
</body>
</html>